package com.example.computer_component_manager.fragment.impl

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.example.computer_component_manager.R
import com.example.computer_component_manager.activity.CpuEditorActivity
import com.example.computer_component_manager.bean.AllCpuInfo
import com.example.computer_component_manager.databinding.CpuItemBinding
import com.example.computer_component_manager.databinding.FragmentComponentRecyclerBinding
import com.example.computer_component_manager.fragment.ComponentListFragment
import com.example.computer_component_manager.fragment.impl.CpuFragment.Companion.allCpuInfo
import com.example.computer_component_manager.util.AnimateUtil
import com.example.computer_component_manager.util.DbUtil
import com.example.computer_component_manager.util.ToastUtil
import com.example.computer_component_manager.volley.MyJsonArrayRequest
import com.example.computer_component_manager.volley.MyJsonObjectRequest
import com.example.computer_component_manager.volley.VolleyApplication

/**
 * CPU管理界面碎片(Fragment)
 * @property binding layout结合类（新用法，可以直接调用布局里的属性）
 * @property adapter CPU列表适配器
 * @property allCpuInfo CPU信息（继承自列表的对象）
 *
 * @author 1923111015董寺卓
 */

class CpuFragment : ComponentListFragment() {

    companion object {

        var allCpuInfo: AllCpuInfo = AllCpuInfo()

    }

    private lateinit var binding: FragmentComponentRecyclerBinding

    private val adapter = CpuAdapter()

    /**
     * 实现：刷新数据方法
     * 获取CPU信息
     * 最后调用CPU Fragment适配器的列表更改方法
     */
    override fun refreshData() {
        val getAllCpuInfoRequest = MyJsonArrayRequest(
            Request.Method.GET, DbUtil.GET_ALL_CPU_INFO_URL, null, {
                allCpuInfo = DbUtil.gson.fromJson(it.toString(), AllCpuInfo::class.java)
                closeAllItem()
                adapter.notifyDataSetChanged()
            }, {
                ToastUtil.showShortError(context)
            })
        VolleyApplication.instance.requestQueue.add(getAllCpuInfoRequest)
    }

    override fun closeAllItem() {
        for (i in 0..adapter.itemCount) {
            binding.rvComponentList.findViewHolderForAdapterPosition(i)
                ?.itemView?.findViewById<TableLayout>(R.id.tlCpuItemInfo)?.visibility = View.GONE
        }
    }

    /**
     * 跳转到CPU编辑器页面
     *
     * @param position 此值可为null(null表示添加，非null表示更新)
     */
    override fun gotoItemEditor(position: Int?) {
        // 获取品牌信息
        val gotoEditorRequest = MyJsonArrayRequest(
            Request.Method.GET, DbUtil.GET_CPU_BRANDS_URL, null, {
                val intent = Intent(context, CpuEditorActivity::class.java)
                position?.let { value -> intent.putExtra("cpuItemPosition", value) }
                intent.putExtra("cpuBrands", it.toString())
                startActivityForResult(intent, DbUtil.CPU_EDITOR_REQUEST_CODE)
            }, {
                ToastUtil.showShortError(context)
            })
        VolleyApplication.instance.requestQueue.add(gotoEditorRequest)
    }

    /**
     * 删除信息方法
     */
    override fun deleteItem(position: Int) {
        val cpuInfoItem = allCpuInfo[position]
        val delCpuItemRequest = MyJsonObjectRequest(Request.Method.DELETE,
            "${DbUtil.API_PREFIX}/cpu/${cpuInfoItem.id}",
            null, {
                ToastUtil.showShortSuccess(context, it.optString("msg"))
                refreshData()
            }, {
                ToastUtil.showShortError(context)
            })
        VolleyApplication.instance.requestQueue.add(delCpuItemRequest)
    }

    /**
     * 重写 创建视图时 方法
     *
     * @return 处理后的视图
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        binding = FragmentComponentRecyclerBinding.inflate(inflater)
        binding.rvComponentList.layoutManager = LinearLayoutManager(context)
        binding.rvComponentList.adapter = adapter
        refreshData()
        binding.ibRefresh.setOnClickListener { refreshData() }
        binding.ibAdd.setOnClickListener { gotoItemEditor(null) }
        return binding.root
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == DbUtil.CPU_EDITOR_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Toast.makeText(
                context, resources.getString(R.string.success), Toast.LENGTH_SHORT).show()
            refreshData()
        }
    }

    /**
     * CPU适配器（内部）类
     * 使用内部类CpuHolder作为泛型
     */
    inner class CpuAdapter : RecyclerView.Adapter<CpuAdapter.CpuHolder>() {

        /**
         * ViewHolder（内部）类
         */
        inner class CpuHolder(val binding: CpuItemBinding) : RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CpuHolder {
            val binding = CpuItemBinding.inflate(layoutInflater, parent, false)
            binding.root.setOnClickListener {
                if (binding.tlCpuItemInfo.visibility == View.GONE) {
                    binding.tlCpuItemInfo.startAnimation(AnimateUtil.getVisibleAnimation())
                    binding.tlCpuItemInfo.visibility = View.VISIBLE
                } else {
                    binding.tlCpuItemInfo.startAnimation(AnimateUtil.getGoneAnimation())
                    binding.tlCpuItemInfo.visibility = View.GONE
                }
            }
            return CpuHolder(binding)
        }

        /**
         * 更改binding数据
         */
        override fun onBindViewHolder(holder: CpuHolder, position: Int) {
            val cpu = allCpuInfo[position]
            holder.binding.tvCpuItemType.text = cpu.type
            holder.binding.tvCpuItemPrice.text =
                resources.getString(R.string.yuan_format).format(cpu.customerPrice)
            holder.binding.tvCpuItemBrandName.text = cpu.brand.name
            holder.binding.tvCpuItemLithography.text =
                resources.getString(R.string.nm_format).format(cpu.lithography)
            holder.binding.tvCpuItemMaxTurboFrequency.text =
                resources.getString(R.string.frequency_ghz_format).format(cpu.maxTurboFrequency)
            holder.binding.tvCpuItemCoreInfo.text = resources.getString(R.string.core_info_format)
                .format(cpu.coreNumber, cpu.threadNumber)
            holder.binding.btnCpuEdit.setOnClickListener { gotoItemEditor(position) }
            holder.binding.root.setOnLongClickListener {
                AlertDialog.Builder(context)
                    .setTitle(resources.getString(R.string.confirm_del))
                    .setPositiveButton(resources.getString(R.string.ok)) { _, _ ->
                        deleteItem(position)
                    }.setNegativeButton(resources.getString(R.string.cancel)) { _, _ -> }.show()
                return@setOnLongClickListener true
            }
        }

        /**
         * 简便方法表达
         */
        override fun getItemCount() = allCpuInfo.size

    }


}